package pikes.peak;

import java.io.IOException;
import java.util.Map;

import org.springframework.web.servlet.support.RequestContext;

import pikes.core.Printable;
import pikes.ecma.FormattingScriptPrinter;
import pikes.ecma.SourceElements;
import pikes.ecma.SyntaxTreeVisitor;
import pikes.html.xhtml.Script;

public class EcmaScriptCode implements ClientSideScript {

	private ScriptFormattingConfiguration scriptFormattingConfiguration = ScriptFormattingConfiguration.SIMPLE;

	private SourceElements code = null;

	public EcmaScriptCode() {
		this(new SourceElements());
	}

	public EcmaScriptCode(final SourceElements code) {
		super();
		this.code = code;
	}

	public final Script createHtml(Map model, RequestContext requestContext) throws Exception {
		Script script = new Script("text/javascript");

		createEcmaScript(code, model, requestContext);

		script.setCode(new FormattedEcmaScript(code, scriptFormattingConfiguration));

		return script;
	}

	protected void createEcmaScript(SourceElements sourceElements, Map model, RequestContext requestContext)
			throws Exception {

	}

	public final void setScriptFormattingConfiguration(ScriptFormattingConfiguration scriptFormattingConfiguration) {
		if (scriptFormattingConfiguration == null) {
			this.scriptFormattingConfiguration = ScriptFormattingConfiguration.SIMPLE;
		}
		else {
			this.scriptFormattingConfiguration = scriptFormattingConfiguration;
		}

	}

	public final ScriptFormattingConfiguration getScriptFormattingConfiguration() {
		return scriptFormattingConfiguration;
	}

}

class FormattedEcmaScript implements Printable {

	private SourceElements sourceElements = null;

	private ScriptFormattingConfiguration scriptFormattingConfiguration = null;

	public FormattedEcmaScript(final SourceElements sourceElements,
			final ScriptFormattingConfiguration scriptFormattingConfiguration) {
		super();
		this.sourceElements = sourceElements;
		this.scriptFormattingConfiguration = scriptFormattingConfiguration;
	}

	public final void print(Appendable appendable) throws IOException {
		SyntaxTreeVisitor syntaxTreeVisitor = scriptFormattingConfiguration.createScriptSyntaxVisitor(appendable);
		if (syntaxTreeVisitor == null) {
			syntaxTreeVisitor = new FormattingScriptPrinter(appendable);
		}

		sourceElements.visit(syntaxTreeVisitor);

	}

}